dimas.isURL   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 18
rs 9.8
c 0
b 0
f 0
cc 3
1
var ORIGIN = null as any;
2
if (isnode()) {
3
  const process = require("process");
4
  ORIGIN = process.cwd();
5
} else {
6
  ORIGIN = location.protocol + "//" + location.host + location.pathname;
7
}
8
var IP: string;
9
10
class dimas {
11
  /**
12
   * Disabling button
13
   * @param t element of button
14
   * @param V
15
   */
16
  disable_button(t: JQuery<any> | HTMLButtonElement, V: any = null) {
17
    var el: HTMLButtonElement;
18
    if (t instanceof jQuery) {
19
      el = t.get();
20
    } else if (t instanceof HTMLButtonElement) {
21
      el = t;
22
    }
23
    if (typeof el != "undefined") {
24
      el.setAttribute("disabled", "true");
25
    }
26
  }
27
  /**
28
   * Enabling button
29
   * @param t element of button
30
   * @param V
31
   */
32
  enable_button(t: JQuery<any> | HTMLButtonElement, V: any = null) {
33
    var el: HTMLButtonElement;
34
    if (t instanceof jQuery) {
35
      el = t.get();
36
    } else if (t instanceof HTMLButtonElement) {
37
      el = t;
38
    }
39
    if (typeof el != "undefined") {
40
      el.removeAttribute("disabled");
41
    }
42
  }
43
  /**
44
   * get current url without querystrings
45
   */
46
  static url = ORIGIN;
47
  static ip: any = null;
48
  static setIp(ip: any) {
49
    this.ip = ip;
50
    IP = ip;
51
  }
52
  static getIp() {
53
    return this.ip;
54
  }
55
56
  /**
57
   * framework captcha
58
   */
59
  static captcha = {
60
    /**
61
     * DO NOT ASSIGN THIS
62
     */
63
    check: null as NodeJS.Timer,
64
    /**
65
     * Get current captcha id
66
     */
67
    id(header_name: string | null): string {
68
      if (!this.captcha.check) {
69
        this.captcha.get(header_name);
70
      }
71
      return storage().get("captcha");
72
    },
73
    /**
74
     * Get current captcha from backend
75
     * And process it by jsonpCallback
76
     */
77
    get(header_name: null | string): void {
78
      if (!this.captcha.check) {
79
        this.captcha.check = setTimeout(() => {
80
          this.captcha.get(header_name);
81
        }, 60000);
82
      }
83
      var ua = md5(navigator.userAgent).rot13();
84
85
      $.ajax({
86
        url: this.url + "?login=" + guid(),
87
        method: "POST",
88
        headers: {
89
          Accept: "application/javascript",
90
          [header_name]: ua,
91
          [IP.rot13()]: ua,
92
        },
93
        dataType: "jsonp",
94
        jsonpCallback: "framework().captcha.jspCallback",
95
      });
96
    },
97
98
    callback(arg?: any) {},
99
100
    /**
101
     * Captcha JSONP callback
102
     */
103
    jspCallback(res: { captcha: string }) {
104
      if (res.hasOwnProperty("captcha")) {
105
        storage().set("captcha", res.captcha.rot13());
106
        this.captcha.callback(storage().get("captcha"));
107
        this.captcha.listen();
108
      }
109
    },
110
    listener_started: null as any | string,
111
    /**
112
     * Form Captcha listener
113
     */
114
    listen() {
115
      if (this.captcha.listener_started) {
116
        return null;
117
      }
118
      this.captcha.listener_started = new Date().toISOString();
119
      return $(document).on("focus", "form[captcha]", function (e) {
120
        var captcha = $(this).find('[name="captcha"]');
121
        if (!captcha.length) {
122
          $(this).append(
123
            '<input type="hidden" name="captcha" id="' + guid() + '" />'
124
          );
125
          captcha = $(this).find('[name="captcha"]');
126
        }
127
        if (captcha.length) {
128
          captcha.val(storage().get("captcha").rot13());
129
        }
130
        var form = captcha.parents("form");
131
        var button = form.find('[type="submit"]');
132
        form.one("submit", function (e) {
133
          e.preventDefault();
134
          console.log("submit with captcha");
135
          button.prop("disabled", true);
136
          this.captcha.callback = function () {
137
            button.prop("disabled", false);
138
          };
139
          this.captcha.get(null);
140
          form.off("submit");
141
        });
142
        //captcha.parents('form').find('[type="submit"]').one('click', function());
143
      });
144
    },
145
  };
146
147
  /**
148
   * Count Array/Object/String length
149
   * @param {any[]|string|object} data
150
   */
151
  count(data: any[] | string | object) {
152
    if (Array.isArray(data) || typeof data == "string") {
153
      return data.length;
154
    } else if (typeof data == "object") {
155
      return Object.keys(data).length;
156
    } else if (typeof data == "number") {
157
      return data;
158
    }
159
  }
160
161
  /**
162
   * Make async function
163
   * @param callback
164
   */
165
  async(callback: any) {
166
    return new Promise(function (resolve, reject) {
167
      if (typeof callback == "function") {
168
        callback();
169
      }
170
      resolve(true);
171
    });
172
  }
173
174
  /**
175
   * Rupiah currency auto format
176
   */
177
  rp(angka: number, prefix: string | any = null) {
178
    if (!prefix) {
179
      prefix = "Rp. ";
180
    }
181
    var number_string = angka.toString().replace(/[^,\d]/g, ""),
182
      split = number_string.split(","),
183
      sisa = split[0].length % 3,
184
      rupiah = split[0].substr(0, sisa),
185
      ribuan = split[0].substr(sisa).match(/\d{3}/gi);
186
    if (ribuan) {
187
      var separator = sisa ? "." : "";
188
189
      rupiah += separator + ribuan.join(".");
190
    }
191
192
    rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
193
    return !prefix ? rupiah : prefix + " " + rupiah;
194
  }
195
196
  /**
197
   * Check if variable is number / numeric
198
   * @param {String|Number} v
199
   */
200
  isNumber(v: string | number) {
201
    return (
202
      !isNaN(parseInt(v.toString()) - parseFloat(v.toString())) &&
203
      /^\d+$/.test(v.toString())
204
    );
205
  }
206
207
  /**
208
   * Check if valid url
209
   * @param url url address
210
   */
211
  isURL(url: string) {
212
    if (url.startsWith("/")) {
213
      console.log("url type is local");
214
      return true;
215
    }
216
    let result: URL;
217
    try {
218
      result = new URL(url);
219
    } catch (_) {
220
      return false;
221
    }
222
223
    return result.protocol === "http:" || result.protocol === "https:";
224
  }
225
226
  /**
227
   * Check url is valid and reachable
228
   * @param url url address
229
   * @param callback callback function
230
   */
231
  isURLReachable(url: string, callback: (arg0: boolean, arg1: string) => any) {
232
    if (this.isURL(url)) {
233
      var myRequest = new Request(url);
234
235
      fetch(myRequest).then(function (response) {
236
        console.log(`${response.status} - ${url}`);
237
        if (response.status == 200) {
238
          callback(true, url);
239
        }
240
      });
241
    }
242
  }
243
244
  /**
245
   * strpad / startwith zero [0]
246
   * @param {number} val
247
   */
248
  strpad(val: number) {
249
    if (val >= 10) {
250
      return val;
251
    } else {
252
      return "0" + val;
253
    }
254
  }
255
256
  /**
257
   * Autofill datetime-local value
258
   */
259
  datetimelocal(v?: string | number) {
260
    var d = !v ? new Date() : new Date(v);
261
    $("input[type=datetime-local]").val(
262
      d.getFullYear() +
263
        "-" +
264
        this.strpad(d.getMonth() + 1) +
265
        "-" +
266
        this.strpad(d.getDate()) +
267
        "T" +
268
        this.strpad(d.getHours()) +
269
        ":" +
270
        this.strpad(d.getMinutes())
271
    );
272
  }
273
274
  /**
275
   * Get cookie
276
   * @param string name cookie
277
   */
278
  gc(name: string) {
279
    var nameEQ = name + "=";
280
    var ca = document.cookie.split(";");
281
    for (var i = 0; i < ca.length; i++) {
282
      var c = ca[i];
283
      while (c.charAt(0) == " ") {
284
        c = c.substring(1, c.length);
285
        if (c.indexOf(nameEQ) == 0) {
286
          return c.substring(nameEQ.length, c.length);
287
        }
288
      }
289
    }
290
291
    return null;
292
  }
293
294
  /**
295
   * Odd or Even (Ganjil Genap);
296
   * @param type odd or even
297
   */
298
  oddoreven(n: string, type: string) {
299
    if (!type) {
300
      type = "odd";
301
    }
302
    var time = !n ? new Date().getDay() : Number(n);
303
304
    if (!/^-{0,1}\d+jQuery/.test(time.toString())) {
305
      alert("arguments is not number, please remove quote");
306
      return null;
307
    }
308
309
    var hasil = time % 2;
310
311
    var type = /^(odd|ganjil)$/.test(type) ? "1" : "0";
312
    //return hasil == (type == ('odd' || 'ganjil') ? 1 : 0);
313
314
    return hasil.toString() == type.toString();
315
  }
316
317
  /**
318
   * Set cookie
319
   * @param {String} name
320
   * @param {any} value
321
   * @param {number} hours
322
   */
323
  sc(name: string, value: any, hours: number) {
324
    var expires = "";
325
    if (hours) {
326
      var date = new Date();
327
      date.setTime(date.getTime() + hours * 3600 * 1000);
328
      expires = "; expires=" + date.toUTCString();
329
    }
330
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
331
  }
332
333
  allcookies() {
334
    var pairs = document.cookie.split(";");
335
    var cookies: { [key: string]: any } = {};
336
    for (var i = 0; i < pairs.length; i++) {
337
      var pair = pairs[i].split("=");
338
      var str: string = pair[0].trim();
339
      cookies[str] = unescape(pair.slice(1).join("="));
340
    }
341
    return cookies;
342
  }
343
344
  /**
345
   * Remove Cookie
346
   */
347
  rc(name: string): void {
348
    document.cookie = name + "=; Max-Age=-99999999;";
349
  }
350
351
  /**
352
   * Get Query name from current url
353
   */
354
  getquery(variable: any) {
355
    var query = window.location.search.substring(1);
356
    var vars = query.split("&");
357
    for (var i = 0; i < vars.length; i++) {
358
      var pair = vars[i].split("=");
359
      if (pair[0] == variable) {
360
        return pair[1];
361
      }
362
    }
363
    return false;
364
  }
365
366
  recode(content: string, passcode: string) {
367
    var result = [];
368
    var str = "";
369
    var codesArr = JSON.parse(content);
370
    var passLen = passcode.length;
371
    for (var i = 0; i < codesArr.length; i++) {
372
      var passOffset = i % passLen;
373
      var calAscii = codesArr[i] - passcode.charCodeAt(passOffset);
374
      result.push(calAscii);
375
    }
376
    for (var i = 0; i < result.length; i++) {
377
      var ch = String.fromCharCode(result[i]);
378
      str += ch;
379
    }
380
    return str;
381
  }
382
383
  /**
384
   * Get js file from url
385
   * @param {String} url
386
   * @param {Function} callback
387
   */
388
  js(url: string, callback: Function | any) {
389
    var pel = document.body || document.head;
390
    var script = document.createElement("script");
391
    script.type = "text/javascript";
392
    script.src = url;
393
    if (typeof callback == "function") script.onreadystatechange = callback;
394
395
    script.onload = callback;
396
    pel.appendChild(script);
397
  }
398
399
  /**
400
   * Countdown trigger
401
   * @param {JQuery} elm
402
   */
403
  pctdRUN(elm: JQuery) {
404
    var tl = parseInt(elm.attr("countdown")) > 0 ? elm.attr("countdown") : 5,
405
      bs = elm.data("base") ? elm.data("base") : "bg-info",
406
      bw = elm.data("warning") ? elm.data("warning") : "bg-danger",
407
      bc = elm.data("success") ? elm.data("success") : "bg-success",
408
      countdown = elm.progressBarTimer({
409
        warningThreshold: 5,
410
        timeLimit: tl,
411
412
        // base style
413
        baseStyle: bs,
414
415
        // warning style
416
        warningStyle: bw,
417
418
        // complete style
419
        completeStyle: bc,
420
421
        // should the timer be smooth or stepping
422
        smooth: true,
423
424
        // striped progress bar
425
        striped: true,
426
427
        // animated stripes
428
        animated: true,
429
430
        // height of progress bar
431
        // 0 = default height
432
        height: 0,
433
        onFinish() {
434
          var callback = elm.data("callback");
435
          if (callback) {
436
            var xn = window[callback];
437
            if (typeof xn == "function") {
438
              var x = eval(callback);
439
              x();
440
            } else {
441
              console.log(callback + " isn't function ");
442
            }
443
          }
444
        },
445
        label: {
446
          show: true,
447
          type: "percent", // or 'seconds' => 23/60
448
        },
449
        autoStart: true,
450
      });
451
    return countdown;
452
  }
453
454
  /**
455
   * Progress Countdown
456
   * @param {JQuery} elm
457
   */
458
  pctd(elm: JQuery) {
459
    var t = this;
460
461
    if (typeof progressBarTimer == "undefined") {
462
      this.js(
463
        "https://cdn.jsdelivr.net/gh/dimaslanjaka/Web-Manajemen@master/js/jquery.progressBarTimer.js",
464
        function () {
465
          t.pctdRUN(elm);
466
        }
467
      );
468
    } else {
469
      window.onload = function (params: any) {
470
        this.pctdRUN(elm);
471
      };
472
    }
473
  }
474
475
  /**
476
   * Parseurl just like as parse_url at php
477
   */
478
  parseurl(url: string) {
479
    var parser = document.createElement("a"),
480
      searchObject: { [key: string]: any } = {},
481
      queries: string[],
482
      split: any[],
483
      i: number;
484
    // Let the browser do the work
485
    parser.href = url;
486
    // Convert query string to object
487
    queries = parser.search.replace(/^\?/, "").split("&");
488
    for (i = 0; i < queries.length; i++) {
489
      split = queries[i].split("=");
490
      searchObject[split[0]] = split[1];
491
    }
492
    return {
493
      protocol: parser.protocol,
494
      host: parser.host,
495
      hostname: parser.hostname,
496
      port: parser.port,
497
      pathname: parser.pathname,
498
      search: parser.search,
499
      searchObject: searchObject,
500
      hash: parser.hash,
501
      protohost: parser.protocol + "//" + parser.host,
502
    };
503
  }
504
}
505
506
/**
507
 * Framework object initializer
508
 */
509
function framework() {
510
  return new dimas();
511
}
512
513
class app {
514
  static base = "/src/MVC/themes/assets/js/";
515
  static setbase(path: string) {
516
    this.base = path;
517
  }
518
519
  static direct(...args: string[]) {
520
    var scripts = document.querySelectorAll("script[src]");
521
    var last = scripts[scripts.length - 1];
522
    var lastsrc = last.getAttribute("src");
523
    var parsed = framework().parseurl(lastsrc);
524
    args.forEach(function (src) {
525
      this.js(`${app.base}${src}${parsed.search}`, function () {
526
        console.log(`${src} engine inbound`);
527
      });
528
    });
529
  }
530
531
  static load(...args: any[]) {
532
    var scripts = document.querySelectorAll("script[src]");
533
    var last = scripts[scripts.length - 1];
534
    var lastsrc = last.getAttribute("src");
535
    var parsed = framework().parseurl(lastsrc);
536
    args.forEach(function (key, index) {
537
      console.log(key, app.base);
538
      let src: string = "";
539
      if (/^(ajx|ajaxjQuery|ajxjquery|ajquery)$/s.test(key)) {
540
        src = "ajaxJquery.js";
541
      } else if (/^(ajv|ajaxVanilla|ajaxv|avanilla)$/s.test(key)) {
542
        src = "ajaxVanilla.js";
543
      }
544
545
      if (src != "") {
546
        this.js(`${app.base}${src}${parsed.search}`, function () {
547
          console.log(`${src} engine inbound`);
548
        });
549
      }
550
    });
551
  }
552
}
553
554
if (typeof module !== "undefined" && module.exports) {
555
  module.exports.app = app;
556
  module.exports.dimas = dimas;
557
}
558
559
//app.direct('Array.js', 'Object.js', 'saver.js', 'user.js');
560